package com.ppp.searchHelp.core;

import java.io.IOException;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;

import com.aliyun.opensearch.CloudsearchDoc;
import com.ppp.searchHelp.Constant;
import com.ppp.searchHelp.exception.SystemException;
import com.ppp.searchHelp.util.StringUtil;

public class CloudsearchDocHelp {

	public Map<String, Object> getDetail(String id) {
		CloudsearchDoc doc = PPPCore.getMe().getCloudsearchDoc();

		//Map<String, Object> result = new HashMap<>();

		try {
			String json = doc.detail(id);
			System.out.println(json);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void addAndPush(Map<String, Object> fields) {
		CloudsearchDoc doc = PPPCore.getMe().getCloudsearchDoc();

		doc.add(fields);

		try {
			doc.push(Constant.tableName);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void updateAndPush(Map<String, Object> fields) {
		CloudsearchDoc doc = PPPCore.getMe().getCloudsearchDoc();

		doc.update(fields);

		try {
			doc.push(Constant.tableName);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void removeAndPush(Map<String, Object> fields) {
		CloudsearchDoc doc = PPPCore.getMe().getCloudsearchDoc();

		doc.remove(fields);

		try {
			doc.push(Constant.tableName);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 多次操作字段：add/update/delete后再push到阿里。
	 * <br>
	 * 当第一次操作 add/update/delete 时实例化，push时再销毁。
	 */
	CloudsearchDoc doc = null;
	public void add(Map<String, Object> fields){
		if(doc == null)
			doc = PPPCore.getMe().getCloudsearchDoc();
		
		doc.add(fields);
	}
	
	public void update(Map<String, Object> fields){
		if(doc == null)
			doc = PPPCore.getMe().getCloudsearchDoc();
		
		doc.update(fields);
	}
	
	public void remove(Map<String, Object> fields){
		if(doc == null)
			doc = PPPCore.getMe().getCloudsearchDoc();
		
		doc.remove(fields);
	}
	
	public void push() throws ClientProtocolException, IOException{
		
		if(doc == null)
			throw new IllegalAccessError("没有要更新的字段");
		
		String result = doc.push(Constant.tableName);
		JSONObject json = new JSONObject(result);
		
		if(!json.has("status") || json.getString("status").equals("FAIL")){
			throw new SystemException(StringUtil.isBlank(result)?"推送文档失败":result);
		}
		
		doc = null;
	}
}
